<template>
  <div class="score-page">
    <!-- 标签页导航 -->
    <el-tabs v-model="activeTab" class="custom-tabs" :loading="loading">
      <el-tab-pane label="所有成绩" name="all"></el-tab-pane>
      <el-tab-pane label="通过" name="1"></el-tab-pane>
      <el-tab-pane label="未通过" name="2"></el-tab-pane>
    </el-tabs>

    <!-- 内容区域 -->
    <div class="score-list">
      <!-- 加载状态 -->
      <el-skeleton v-if="loading && scores.length === 0" :rows="3" class="skeleton-loading"></el-skeleton>

      <!-- 成绩卡片列表 -->
      <el-card
        v-for="item in filteredScores"
        :key="item.id"
        class="score-card"
        v-else
      >
        <div class="card-header">
          <!-- 动态展示班级名称：特设培训特殊处理 -->
          <span class="score-name">
            {{ item.trainType }}
            <template v-if="item.trainType !== '特设培训'">：{{ item.className }}</template>
          </span>
          <span class="score-tag" :class="getTagClass(item)">{{ item.examResultText }}</span>
        </div>

        <div class="score-info">
          <div class="info-row">
            <!-- 常规/定制培训显示班级编号，特设培训隐藏 -->
            <div class="info-item" v-if="item.trainType !== '特设培训'">
              <span class="label">班级编号：</span>
              <span class="value">{{ item.classNo }}</span>
            </div>
            <div class="info-item">
              <span class="label">培训类型：</span>
              <span class="value">{{ item.trainType }}</span>
            </div>
            <!-- 常规/定制培训显示培训项目，特设培训隐藏 -->
            <div class="info-item" v-if="item.trainType !== '特设培训'">
              <span class="label">培训项目：</span>
              <span class="value">{{ item.project }}</span>
            </div>
          </div>

          <!-- 基础成绩展示 -->
          <div class="info-row">
            <div class="info-item">
              <span class="label">理论成绩：</span>
              <span class="value">{{ item.theoryResult || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">实操成绩：</span>
              <span class="value">{{ item.practicalResult || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">考试结果：</span>
              <span class="value">{{ item.examResultText }}</span>
            </div>
          </div>

          <!-- 补考成绩展示（有补考成绩时显示） -->
          <div class="info-row" v-if="item.makeUpResult">
            <div class="info-item">
              <span class="label">补考成绩：</span>
              <span class="value">{{ item.makeUpResult }}</span>
            </div>
          </div>

          <!-- 补考相关配置 -->
          <div class="info-row">
            <div class="info-item">
              <span class="label">是否为补考：</span>
              <span class="value">{{ item.isRetestText }}</span>
            </div>
            <div class="info-item">
              <span class="label">是否可补考：</span>
              <span class="value">{{ item.canRetestText }}</span>
            </div>
            <div class="info-item">
              <span class="label">是否可二次报名：</span>
              <span class="value">{{ item.canReapply ? '是' : '否' }}</span>
            </div>
          </div>

          <!-- 操作按钮区域：查看试卷 + 去补考 -->
          <div class="card-actions">
            <!-- 查看试卷按钮：特设培训/未知培训类型 不显示 -->
            <el-button
              v-if="item.trainType !== '特设培训' && item.trainType !== '未知培训类型'"
              type="primary"
              size="mini"
              @click="showPaper(item)"
              :loading="item.paperLoading"
            >
              查看试卷
            </el-button>

            <!-- 去补考按钮：未通过的成绩才显示 -->
            <el-button
              v-if="item.examResult === '2'"
              type="warning"
              size="mini"
              @click="goMakeUp(item)"
              :loading="item.makeUpLoading"
              :disabled="item.canRetestText !== '可补考'"
            >
              去补考
              <template v-if="item.canRetestText !== '可补考'">（不可补考）</template>
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 空状态提示 -->
      <div v-if="!loading && filteredScores.length === 0" class="empty-state">
        <el-empty description="暂无成绩数据"></el-empty>
      </div>
    </div>

    <!-- 试卷详情弹窗 -->
    <el-dialog
      title="试卷详情"
      :visible="dialogVisible"
      width="70%"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-loading v-if="paperLoading" fullscreen></el-loading>
      <div v-if="currentScore" class="paper-detail">
        <div class="paper-header">
          <!-- <h3>{{ currentScore.className }} </h3> -->
          <div class="paper-meta">
            <span>培训类型：{{ currentScore.trainType }}</span>
            <span>成绩结果：{{ currentScore.examResultText }}</span>
            <span>理论成绩：{{ currentScore.theoryResult || '-' }}</span>
            <!-- <span>实操成绩：{{ currentScore.practicalResult || '-' }}</span> -->
          </div>
        </div>

        <div class="paper-content">
          <template v-if="paperData.questions && paperData.questions.length">
            <!-- 按题型分组渲染 -->
            <div v-for="(section, secIndex) in paperData.questions" :key="secIndex">
              <h4>
                {{ secIndex + 1 }}、{{ section.title }}
                （共{{ section.items.length }}题，每题{{ section.score }}分）
              </h4>
              <!-- 单个题目 -->
              <div v-for="(question, qIndex) in section.items" :key="qIndex" class="question-item">
                <p class="question-content">
                  {{ qIndex + 1 }}. {{ question.content }}
                </p>

                <!-- 单选/多选题选项 -->
                <div class="options" v-if="question.type === 'choice' && question.options.length">
                  <p v-for="(option, oIndex) in question.options" :key="oIndex">
                    {{ String.fromCharCode(65 + oIndex) }}. {{ option.content }}
                    <span class="correct-answer" v-if="option.isCorrect">（正确答案）</span>
                  </p>
                </div>

                <!-- 答题情况展示 -->
                <div class="answer-status">
                  <p><span class="label">正确答案：</span>{{ question.referenceAnswer }}</p>
                  <p><span class="label">你的答案：</span>{{ question.studentAnswer }}</p>
                  <p><span class="label">解析：</span>{{ question.analysis }}</p>
                </div>

                <hr class="question-divider" v-if="qIndex < section.items.length - 1">
              </div>
            </div>
          </template>
          <div v-else>
            <el-empty description="暂无试卷详情数据"></el-empty>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getExamList, getExamRecordInfo } from "@/api/examination/examRecord";
import { getStudentGradeInfo } from "@/api/training/students";

export default {
  name: "ScorePage",
  props: {
    userId: {
      type: String,
      required: true,
      default: "",
    },
  },
  data() {
    return {
      activeTab: "all",
      dialogVisible: false,
      currentScore: null,
      scores: [],
      paperData: { questions: [] }, // 初始化试卷数据结构
      loading: false,
      paperLoading: false,
      // 后台字典常量映射（统一维护）
      DICT: {
        // 报名类型（培训类型）
        signUpCategory: {
          special: "特设培训",
          regular: "常规培训",
          custom: "定制培训",
        },
        // 考试结果
        examResult: {
          "1": "已通过",
          "2": "未通过",
        },
        // 是否可补考
        makeUpStatus: {
          "1": "可补考",
          "2": "不可补考",
        },
      },
      // 二次报名默认值（后台无此字段）
      canReapply: false,
    };
  },
  watch: {
    userId: {
      handler(newVal) {
        newVal && this.getScoreList();
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    // 根据标签页筛选成绩（适配后台examResult的1/2值）
    filteredScores() {
      if (this.activeTab === "all") return this.scores;
      return this.scores.filter((item) => item.examResult === this.activeTab);
    },
  },
  methods: {
    // 获取成绩列表
    async getScoreList() {
      this.loading = true;
      try {
        const res = await getStudentGradeInfo(this.$store.state.user.studentId);
        if (res.code === 200) {
          this.scores = res.rows.map((item, index) => this.mapScoreData(item, index));
        } else {
          this.$message.error(`获取成绩失败：${res.msg || "未知错误"}`);
        }
      } catch (error) {
        console.error("成绩列表接口异常：", error);
        this.$message.error("获取成绩列表失败，请稍后重试");
      } finally {
        this.loading = false;
      }
    },

    // 核心：适配后台数据的映射方法（优化版）
    mapScoreData(item, index) {
      const { DICT } = this;
      // 1. 培训类型映射（基于signUpCategory）
      const trainType = DICT.signUpCategory[item.signUpCategory] || "未知培训类型";

      // 2. 处理特设培训的空字段（专属文本）
      const isSpecial = trainType === "特设培训";
      const classNo = isSpecial ? "" : (item.trainingClassCode || "未知编号");
      const className = isSpecial ? "" : (item.trainingClassName || "未知班级");
      const project = isSpecial ? "" : (item.projectName || "未知项目");

      // 3. 考试结果映射
      const examResultText = DICT.examResult[item.examResult] || "未知结果";

      // 4. 补考相关字段映射
      // 是否为补考：makeUpMark有值则为是（后台为补考标记字段）
      const isRetest = !!item.makeUpMark;
      const isRetestText = isRetest ? "是" : "否";
      // 是否可补考：基于makeUpStatus字典
      const canRetestText = DICT.makeUpStatus[item.makeUpStatus] || "未知";

      return {
        id: item.trainingClassId,
        classNo,
        className,
        trainType,
        project,
        theoryResult: item.theoryResult,
        practicalResult: item.practicalResult,
        makeUpResult: item.makeUpResult, // 补考成绩
        examResult: item.examResult, // 原始值（用于筛选）
        examResultText, // 格式化后的考试结果
        isRetest,
        isRetestText,
        canRetestText,
        canReapply: this.canReapply, // 二次报名默认值
        originalData: item, // 透传原始数据
        paperLoading: false, // 查看试卷加载状态
        makeUpLoading: false, // 补考按钮加载状态
        examPaperId: item.examPaperId,
      };
    },

    // 获取标签样式（基于考试结果）
    getTagClass(item) {
      return item.examResult === "1" ? "tag-passed" : "tag-failed";
    },

    // 查看试卷详情（仅常规/定制培训可点击）
    async showPaper(score) {
      // 缓存已加载的试卷数据，避免重复请求
      if (this.currentScore?.id === score.id && this.paperData.questions.length) {
        this.dialogVisible = true;
        return;
      }

      this.paperLoading = true;
      this.currentScore = { ...score, paperLoading: true };

      try {
         const res = await getExamRecordInfo({
          studentId: this.$store.state.user.studentId,
          trainingClassId: score.id,
        });
        // const res = await getExamRecordInfo({
        //   studentId: "1428681975179268096",
        //   trainingClassId: "3",
        // });
        if (res.code === 200) {
          // 筛选目标试卷数据
          // const examRecord = res.rows.find(item => item.examPaperId === "1434204478333014016");
          const examRecord = res.rows.find(item => item.examPaperId === score.examPaperId);
          if (examRecord && examRecord.examRecordInfoDtoList) {
            // 格式化试卷数据为模板所需结构
            this.paperData.questions = this.formatPaperData(examRecord.examRecordInfoDtoList);
          } else {
            this.paperData.questions = [];
            this.$message.warning("未查询到该试卷的详细题目数据");
          }
          this.dialogVisible = true;
        } else {
          this.$message.error(`获取试卷失败：${res.msg || "未知错误"}`);
        }
      } catch (error) {
        console.error("试卷详情接口异常：", error);
        this.$message.error("获取试卷详情失败，请稍后重试");
      } finally {
        this.paperLoading = false;
        if (this.currentScore) this.currentScore.paperLoading = false;
      }
    },

    // 核心：格式化试卷数据为模板所需结构
    formatPaperData(questions) {
      // 题型映射字典（后端questionType：1单选/2多选/3判断）
      const typeMap = {
        "1": { name: "单选题", key: "single", score: 10 },
        "2": { name: "多选题", key: "multiple", score: 10 },
        "3": { name: "判断题", key: "judge", score: 10 },
      };

      // 1. 按题型分组
      const grouped = questions.reduce((acc, question) => {
        const typeConfig = typeMap[question.questionType] || { name: "其他题型", key: "other", score: 10 };
        if (!acc[typeConfig.key]) {
          acc[typeConfig.key] = {
            title: typeConfig.name,
            score: typeConfig.score,
            items: []
          };
        }

        // 2. 处理单个题目数据
        const questionItem = {
          content: question.questionName, // 题干
          type: question.questionType === "3" ? "judge" : "choice", // 题型（判断/选择）
          options: [], // 选项列表（判断题为空）
          referenceAnswer: "", // 正确答案
          studentAnswer: "", // 用户答案
          analysis: question.analysisContent || "无解析" // 解析
        };

        // 3. 处理单选/多选题的选项
        if (question.questionType !== "3" && question.questionOptionList.length) {
          questionItem.options = question.questionOptionList.map(opt => ({
            content: opt.optionContent,
            isCorrect: this.isOptionCorrect(question.answer, opt.optionName, question.questionType)
          }));
          // 格式化正确答案（带选项内容）
          questionItem.referenceAnswer = this.formatCorrectAnswer(question.answer, question.questionOptionList);
        } else if (question.questionType === "3") {
          // 处理判断题答案
          questionItem.referenceAnswer = question.answer === "对" ? "正确" : "错误";
        }

        // 4. 格式化用户答案
        questionItem.studentAnswer = this.formatStudentAnswer(question.studentAnswer, question.questionType);

        acc[typeConfig.key].items.push(questionItem);
        return acc;
      }, {});

      // 5. 转换为数组并按指定顺序展示（单选→多选→判断→其他）
      return [
        grouped.single,
        grouped.multiple,
        grouped.judge,
        grouped.other
      ].filter(Boolean); // 过滤空分组
    },

    // 判断选项是否为正确答案
    isOptionCorrect(correctAnswer, optionName, questionType) {
      if (questionType === "3") return false; // 判断题无选项
      if (questionType === "2") {
        // 多选题：正确答案是ABC这类字符串，拆分后判断
        return correctAnswer?.split("").includes(optionName) || false;
      }
      // 单选题：直接匹配
      return correctAnswer === optionName;
    },

    // 格式化正确答案（带选项内容，如"A. 6"、"A. 白菜、B. 萝卜"）
    formatCorrectAnswer(correctAnswer, options) {
      if (!correctAnswer) return "无";
      if (!options || !options.length) return correctAnswer.split("").join("、");

      // 匹配选项内容并拼接
      return correctAnswer.split("").map(letter => {
        const option = options.find(opt => opt.optionName === letter);
        return option ? `${letter}. ${option.optionContent}` : letter;
      }).join("、");
    },

    // 格式化用户答案
    formatStudentAnswer(studentAnswer, questionType) {
      if (!studentAnswer) return "未作答";
      if (questionType === "3") {
        // 判断题用户答案
        return studentAnswer === "true" ? "正确" : "错误";
      }
      // 单选/多选题：拆分字母并拼接
      return studentAnswer.split("").join("、");
    },

    // 去补考逻辑（需根据实际业务对接接口）
    async goMakeUp(score) {
      // 不可补考直接提示
      if (score.canRetestText !== "可补考") {
        this.$message.warning("当前成绩不可补考");
        return;
      }

      score.makeUpLoading = true;
      try {
        // 此处替换为实际的补考接口调用逻辑
        // 示例：const res = await submitMakeUpApply(score.originalData);
        // if (res.code === 200) {
        //   this.$message.success("补考申请提交成功，请前往补考页面参加考试");
        //   this.$router.push({ path: '/make-up-exam', query: { id: score.id } });
        // } else {
        //   this.$message.error(`补考申请失败：${res.msg || "未知错误"}`);
        // }

        // 临时提示
        this.$message.success("补考申请已提交，请前往补考页面参加考试");
      } catch (error) {
        console.error("补考接口异常：", error);
        this.$message.error("补考申请失败，请稍后重试");
      } finally {
        score.makeUpLoading = false;
      }
    },

    // 关闭弹窗重置数据
    handleDialogClose() {
      this.paperData = { questions: [] };
      this.currentScore = null;
      this.dialogVisible = false;
    },
  },
};
</script>

<style scoped>
.score-page {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

/* 标签页样式 */
.custom-tabs {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

::v-deep .el-tabs__header {
  margin-bottom: 20px;
}

::v-deep .el-tabs__item {
  font-size: 14px;
  color: #6b7280;
  padding: 0 16px;
}

::v-deep .el-tabs__item.is-active {
  color: #165dff;
  font-weight: 500;
}

::v-deep .el-tabs__active-bar {
  background-color: #165dff;
  height: 2px;
}

/* 加载骨架屏 */
.skeleton-loading {
  padding: 16px;
}

/* 成绩列表样式 */
.score-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 卡片样式 */
.score-card {
  border: none;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
}

.score-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f9fafb;
  border-bottom: 1px solid #f0f2f5;
}

.score-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2329;
}

.score-tag {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.tag-passed {
  background-color: #e6f7ee;
  color: #00b42a;
}

.tag-failed {
  background-color: #fff1f0;
  color: #f53f3f;
}

/* 卡片内容区 */
.score-info {
  padding: 16px 20px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 32px;
  margin-bottom: 12px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  display: flex;
  align-items: center;
  min-width: 220px;
}

.label {
  font-size: 14px;
  color: #6b7280;
  margin-right: 8px;
  white-space: nowrap;
}

.value {
  font-size: 14px;
  color: #1f2329;
  line-height: 1.5;
}

/* 卡片操作区 */
.card-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px dashed #e8e8e8;
  gap: 12px; /* 新增：按钮之间的间距 */
}

/* 空状态样式 */
.empty-state {
  padding: 48px 0;
  text-align: center;
}

/* 试卷详情弹窗样式 */
.paper-detail {
  line-height: 1.8;
}

.paper-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.paper-meta {
  margin-top: 10px;
  display: flex;
  gap: 20px;
  color: #6b7280;
  font-size: 14px;
  flex-wrap: wrap;
}

.paper-content h4 {
  margin: 16px 0 10px;
  color: #1f2329;
}

.question-item {
  margin-bottom: 16px;
  padding-left: 10px;
}

.question-content {
  font-size: 15px;
  color: #1f2329;
  margin-bottom: 12px;
}

.options {
  padding-left: 20px;
  margin-top: 8px;
}

.options p {
  margin: 6px 0;
}

.correct-answer {
  color: #00b42a;
  margin-left: 8px;
  font-size: 13px;
}

.answer-status {
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f9fafb;
  border-radius: 4px;
  font-size: 14px;
}

.answer-status .label {
  color: #6b7280;
  margin-right: 8px;
  font-weight: 500;
}

.question-divider {
  border: none;
  border-top: 1px dashed #e8e8e8;
  margin: 16px 0;
}

.answer {
  padding-left: 20px;
  margin-top: 8px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .info-item {
    min-width: 180px;
  }
}

@media (max-width: 768px) {
  .score-page {
    padding: 16px;
  }

  .info-row {
    gap: 12px 16px;
  }

  .info-item {
    min-width: 100%;
  }

  .paper-meta {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
